<template>
  <div :class="{ right: true, animationStart: animationShow.animationStartShow, animationEnd: animationShow.animationEndShow }"><!--  -->
    <img
      @mousewheel.prevent
      v-if="rightOpenOrCloseShow.rightOpenOrClose"
      @click="openOrClose"
      class="openOrClose"
      src="@/assets/screenShowImg/右边展开收起按钮.png"
      alt=""
    />
    <img
      @mousewheel.prevent
      v-else
      class="openOrClose"
      @click="openOrClose"
      src="@/assets/screenShowImg/右边展开收起按钮.png"
      alt=""
    />
    <div class="bigDiv2">
      <div class="carbonDischarge">
        <div class="title">
          <img src="@/assets/screenShowImg/标题组件背景.png" />
          <div>
            <img src="@/assets/screenShowImg/icons-标题.png" />
            <p>设备数量统计</p>
          </div>
        </div>
        <div>
          <div ref="carbonAnalyseEchartsRef" class="carbonAnalyseEcharts"></div>
        </div>
      </div>
      <div class="devDistribution">
        <div class="title">
          <img src="@/assets/screenShowImg/标题组件背景.png" />
          <div>
            <img src="@/assets/screenShowImg/icons-标题.png" />
            <p>设备状态统计</p>
          </div>
        </div>
        <div class="progress">
          <div>
            <el-progress
              type="circle" 
              :percentage="100"
              :stroke-width="10"
              color="#83efea"
            >
              <template #default="{ percentage }">
                <p>{{ statsData.onlineTotal }}<span>个</span></p>
                在线
              </template>
            </el-progress>
          </div>
          <div>
            <el-progress
              type="circle" 
              :percentage="100" 
              :stroke-width="10"
              color="#ffb340"
            >
              <template #default="{ percentage }">
                <p>{{ statsData.offlineTotal }}<span>个</span></p>
                离线
              </template>
            </el-progress>
          </div>
          <div>
            <el-progress
              type="circle" 
              :percentage="100" 
              :stroke-width="10"
              color="gray"
            >
              <template #default="{ percentage }">
                <p>{{ statsData.neverOnlineTotal }}<span>个</span></p>
                待激活
              </template>
            </el-progress>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import * as echarts from 'echarts'
import { stats } from '@/api/index'

const animationShow = reactive({
  animationStartShow: true,
  animationEndShow: false,
})

const statsData = ref({
  categoryTotal: 0,
  productTotal: 0,
  deviceTotal: 0,
  reportTotal: 0,
  onlineTotal: 0,
  offlineTotal: 0,
  neverOnlineTotal: 0,
  deviceStatsOfCategory: [],
  reportDataStats: []
})

let myChart: echarts.ECharts | null = null

onUnmounted(() => {
  window.removeEventListener('resize', resize)
  if (myChart) {
    myChart.dispose() // 清理 echarts 实例
  }
})
onMounted(() => {
  // 先用默认数据绘制图表
  if (carbonAnalyseEchartsRef.value) {
    myChart = echarts.init(carbonAnalyseEchartsRef.value as HTMLElement)
    energyAnalyseData2()
  }
  
  // 获取API数据
  stats().then((res) => {
    statsData.value = {
      ...res.data,
      // 如果API返回的deviceStatsOfCategory为空，保留默认数据
      deviceStatsOfCategory: res.data.deviceStatsOfCategory && res.data.deviceStatsOfCategory.length > 0 
        ? res.data.deviceStatsOfCategory 
        : statsData.value.deviceStatsOfCategory
    }
    
    // 更新图表
    if (carbonAnalyseEchartsRef.value) {
      energyAnalyseData2()
    }
  })
  
  window.addEventListener('resize', resize)

  // 动画
  let a = setTimeout(() => {
    animationShow.animationEndShow = true
    clearTimeout(a)
  }, 100)
  let b = setTimeout(() => {
    animationShow.animationStartShow = false
    animationShow.animationEndShow = false
    clearTimeout(b)
  }, 2500)
})

// 绘制能耗分析图表
const energyAnalyseData2 = () => {
    let xAxis: string[]  = []
    let yAxis: number[] = []
    let data = statsData.value.deviceStatsOfCategory || []
    if (data && data.length > 0) {
      data.forEach((e: { name: string; value: number }) => {
        xAxis.push(e.name)
        yAxis.push(e.value)
      })
      // 能耗分析图表
      energyAnalyseEcharts(xAxis, yAxis)
    } else {
      console.warn('No device stats data available')
    }
}

// 能耗分析图表
const carbonAnalyseEchartsRef = ref<HTMLDivElement | null>(null)
const energyAnalyseEcharts = (h, S) => {
  const myChart = echarts.init(carbonAnalyseEchartsRef.value as HTMLElement)
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(9, 14, 18, 0.8)',
      borderWidth: 0,
      position: function (pos, params, dom, rect, size) {
        // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
        let obj = { top: '10%' }
        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5
        return obj
      },
      textStyle: {
        color: '#fff',
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    grid: {
      left: '8%',
      right: '1%',
      top: '23%',
      bottom: '10%',
    },
    legend: {
      type: 'scroll',
      top: 10,
      right: 0, // 将图例靠右对齐
      itemWidth: 30,
      itemHeight: 10,
      itemGap: 17,
      icon: 'rect',
      textStyle: {
        // color: '#aeaeb2',
        color: 'gray',
        fontSize: 14, // 调整图例字体大小
        padding: 0,
        // 设置图例图形与文字对齐
        height: 12,
        rich: {
          a: {
            verticalAlign: 'middle',
          },
        },
      },
      data: ['设备数量'],
    },
    xAxis: [
      {
        type: 'category',
        data: h,
        axisPointer: {
          type: 'shadow',
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          // 设置X轴标签过长时换行显示
          interval: 0, // 强制显示所有标签
          formatter: function(value) {
            // 当文本长度超过4个字符时自动换行
            if (value.length > 4) {
              return value.substring(0, 4) + '\n' + value.substring(4)
            }
            return value
          },
          fontSize: 14, // 设置X轴标签字体大小
        },
        splitLine: {
          show: false,
          lineStyle: {
            // color: '#92abc31a',
            // color: 'gray',
            width: 1,
            type: 'solid',
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量/个',
        nameTextStyle: {
          fontSize: 14,
          padding: [0, 0, 15, 0] // 添加一些底部边距
        },
        // 添加自定义刻度线控制
        axisLabel: {
          formatter: function(value) {
            // 仅显示整数坐标轴标签，确保返回字符串类型
            if (parseInt(String(value)) === value) {
              return String(value)
            }
            return ''
          },
          fontSize: 14, // 设置Y轴刻度值字体大小
        },
        splitLine: {
          show: true,
          lineStyle: {
            // color: '#ffffff34',
            // color: 'gray',
            width: 1,
            type: 'solid',
          },
        },
      },
    ],
    series: [
      {
        name: '设备数量',
        type: 'bar',
        barWidth: 30,
        barGap: '40%',
        label: {
          show: true,
          position: 'top',
          fontSize: 12, // 设置柱状图上方数值的字体大小
          offset: [0, 4] // 增加与柱状图的距离
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#4ef6f6', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#4ef6f600', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
          borderRadius: [5, 5, 0, 0],
        },
        tooltip: {
          valueFormatter: function (value) {
            return value + ' 个'
          },
        },
        data: S,
      },
    ],
  }
  myChart.setOption(option)
}

// 监听屏幕宽度
const resize = () => {
  //   //根据窗口变化自动调节图表大小
  if (carbonAnalyseEchartsRef.value) {
    const myChart = echarts.getInstanceByDom(carbonAnalyseEchartsRef.value as HTMLElement)
    if (myChart) {
      myChart.resize()
    }
  }
}

const rightOpenOrCloseShow = reactive({
  rightOpenOrClose: true,
})
// 点击折叠图片
const openOrClose = (e) => {
  if (rightOpenOrCloseShow.rightOpenOrClose) {
    e.target.parentNode.classList.add('rightOpenOrClose')
    rightOpenOrCloseShow.rightOpenOrClose = false
  } else {
    e.target.parentNode.classList.remove('rightOpenOrClose')
    rightOpenOrCloseShow.rightOpenOrClose = true
  }
}
</script>
  
<style lang="scss" scoped>
.right {
  display: flex;
  flex-direction: column;
  width: 23.22916%;
  min-width: 410px;
  transition: 0.4s all;
  position: relative;
  z-index: 10;
  padding: 1%;
  height: 100%;
  background-color: rgba(255, 255, 255, 1);
  > img {
    height: 100%;
  }
  > .openOrClose {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translate(-100%, -50%);
  }
  > div.bigDiv2 {
    width: 100%;
    height: 100%;
    > div {
      width: 100%;
      display: flex;
      flex-direction: column;
      div.title {
        width: 100%;
        flex: 0 0 auto;
        position: relative;
        > img {
          width: 100%;
          margin: 0 !important;
        }
        > div {
          position: absolute;
          top: 50%;
          left: 5%;
          transform: translateY(-50%);
          height: 100%;
          display: flex;
          align-items: center;
          > img {
            position: absolute;
            top: 50%;
            left: 0;
            transform: translateY(-50%);
          }
          > p:nth-of-type(1) {
            font-size: 18px;
            font-weight: 600;
            text-indent: 25px;
          }
          > p:nth-of-type(2) {
            margin-top: 4px;
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
      > div {
        width: 100%;
        flex: 1 1 auto;
        overflow: auto;
        > div.tab {
          width: 100%;
          // margin-bottom: 4%;
          margin-bottom: 0%;
          background: url('@/assets/screenShowImg/原子装饰线.png') no-repeat;
          background-size: 51%;
          display: flex;
          justify-content: flex-end;
          padding-right: 1.95%;
          background-position-y: 50%;
          > div {
            width: 46.5%;
            background: #ccf8ff;
            line-height: 25px;
            font-size: 14px;
            // color: rgba(255, 255, 255, 0.564);
            display: flex;
            align-items: center;
            font-family: 'Noto Sans CJK SC';
            p {
              flex: 1;
              text-align: center;
              cursor: pointer;
              margin: 0;
            }
            .active {
              background: url('@/assets/screenShowImg/切换日月年.png') no-repeat;
              background-size: 100%;
            }
          }
        }
      }
    }
    > div.carbonDischarge {
      height: 65%;
      > div > .carbonAnalyseEcharts {
        width: 99%;
        height: 40vh;
      }
      .el-empty {
        margin: 0;
        padding: 0;
        height: 17vh;
        :deep(.el-empty-image) {
          height: 70px;
        }
      }
    }
    > div.devDistribution {
      width: 100%;
      height: 35%;
      // position: relative;
      display: flex;
      flex-direction: column;
      div.title {
        width: 100%;
        flex: 0 0 auto;
        position: relative;
        > img {
          width: 100%;
        }
        > div {
          position: absolute;
          top: 50%;
          left: 5%;
          transform: translateY(-50%);
          height: 100%;
          display: flex;
          align-items: center;
          > img {
            position: absolute;
            top: 50%;
            left: 0;
            transform: translateY(-50%);
          }
          > p:nth-of-type(1) {
            font-size: 18px;
            font-weight: 600;
            text-indent: 25px;
          }
        }
      }
      > div.progress  {
        width: 100%;
        display: flex;
        // height: 100%;
        flex: 1 1 auto;
        overflow: auto;
        > div:nth-of-type(1) {
          width: 33%;
          font-family: 'Source Han Sans CN';
          font-size: 12px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          p {
            font-size: 25px;
            font-family: 'D-DIN';
            margin-bottom: 6%;
            margin-top: 0;
            color: black;
            span {
              font-family: 'D-DIN';
              font-size: 16px;
              color: black;
            }
          }
          :deep(.el-progress) {
            .el-progress-circle {
              width: 110px !important;
              height: 110px !important;
            }
          }
        }
        > div:nth-of-type(2) {
          width: 34%;
          font-family: 'Source Han Sans CN';
          font-size: 12px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          p {
            font-size: 25px;
            font-family: 'D-DIN';
            margin-bottom: 6%;
            margin-top: 0;
            color: black;
            span {
              font-family: 'D-DIN';
              font-size: 16px;
              color: black;
            }
          }
          :deep(.el-progress) {
            .el-progress-circle {
              width: 110px !important;
              height: 110px !important;
            }
          }
        }
        > div:nth-of-type(3) {
          width: 33%;
          font-family: 'Source Han Sans CN';
          font-size: 12px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          p {
            font-size: 25px;
            font-family: 'D-DIN';
            margin-bottom: 6%;
            margin-top: 0;
            color: black;
            span {
              font-family: 'D-DIN';
              font-size: 16px;
              color: black;
            }
          }
          :deep(.el-progress) {
            .el-progress-circle {
              width: 110px !important;
              height: 110px !important;
            }
          }
        }
      }
      // > div.devDistributionEcharts {
      //   width: 100%;
      //   height: 100%;
      //   flex: 1 1 auto;
      //   overflow: auto;
      //   position: relative;
      // }
    }
  }
  > .el-btn {
    position: absolute;
    top: 0;
    left: 0;
    transform: translateX(-100%);
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.right.animationStart {
  transform: translateX(100%);
  > .bigDiv2 {
    > .carbonDischarge {
      transform: translateX(50%);
    }
    > .devDistribution {
      transform: translateX(50%);
    }
  }
}
div.right.animationEnd {
  transition: 2.5s all;
  transform: translateX(0%);
  > .bigDiv2 {
    > .carbonDischarge {
      transition: 2.5s all;
      transform: translateX(0%);
    }
    > .devDistribution {
      transition: 2.5s all;
      transform: translateX(0%);
    }
  }
}
.rightOpenOrClose {
  transition: 0.4s all;
  transform: translateX(100%);
}
</style>
  